package com.wangjiacai.utils.web.filter;

import com.wangjiacai.utils.web.properties.FilterProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class SystemFilter implements Filter {

    @Autowired
    private FilterProperties filterProperties;

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    public SystemFilter(FilterProperties filterProperties) {
        this.filterProperties = filterProperties;
    }

    @Override
	public void destroy() {

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("token");
        if(shouldLog(request)){
            log.info("client ip:{},{}:{},token:{}",request.getRemoteAddr(),request.getMethod(),request.getRequestURL(),token);
        }
        filterChain.doFilter(request,response);
    }

    public boolean shouldLog(HttpServletRequest request) {
        for(String freeUrl:filterProperties.getFreeUrl()){
            if(antPathMatcher.match(freeUrl,request.getRequestURI())){
                return false;
            }
        }
        return true;
    }
}
